// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
/**
 * 全部配置
 */
import AppConfig from '@/config/app';
uni.$appConfig=AppConfig;
/**
 * 缓存配置
 */
import Cache from '@/config/cache';
uni.$cacheConfig=Cache;
/**
 * 工具函數
 */
import Utils from './util.js'
uni.$utils=Utils

/**
 * MD5
 */
import Md5 from './md5.js'
// 小程序登录路径
// #ifdef MP || MP-WEIXIN
 var loginPath='../login-app/login-app'
// #endif
// APP||h5 登录路径
 // #ifdef APP-PLUS || H5
 var loginPath='../login-app/login-app'
// #endif

/**
 * 生成用户访问设备ID  
 */
if(!uni.getStorageSync(uni.$cacheConfig.DEVICE_ID)){
	//uni.setStorageSync(uni.$cacheConfig.DEVICE_ID, uni.$utils.getUuid());
	uni.setStorageSync(uni.$cacheConfig.DEVICE_ID, uni.getDeviceInfo().deviceId);
}
/**
 * 固定发送头部元素
 */
let header={};
header[uni.$cacheConfig.TOKENNAME]=uni.getStorageSync(uni.$cacheConfig.TOKENNAME) || '';
header=Object.assign(uni.$appConfig.HEADER,header);
header[uni.$cacheConfig.DEVICE_ID]=uni.getStorageSync(uni.$cacheConfig.DEVICE_ID);
/**
 *全局 request 请求
 */
let $request=(url,get={},post={},method='get')=>{
	let api_uri=setUrl(url,get || {});
	//console.log(api_uri);
	return new Promise((rosolve,reject)=>{
		uni.request({
			header:header,
			url:api_uri,
			method:method,
			data:post,
			success:({data})=>{
				if(data.error_code == -3000){ //服务器返回 -3000 登录超时
				    uni.setStorageSync(uni.$cacheConfig.TOKENNAME,null);
				    let refresh_token=uni.getStorageSync(uni.$cacheConfig.REFRESH_TOKENNAME);
					if(refresh_token){
						header[uni.$cacheConfig.TOKENNAME]=refresh_token;
						return refreshToken(url,get,post,method,rosolve);
					}
					//[本地没有刷新Token]跳转登录
					//uni.navigateTo({url:loginPath});
					uni.reLaunch({url:loginPath});
				}else{
					rosolve(data)
				}
			}
		})
	})
}
/**
 * 刷新Token
 * @param {Object} url
 * @param {Object} data
 * @param {Object} method
 * @param {Object} rosolve
 */
async function refreshToken(url,get,post,method,rosolve){
	let ret = await uni.$get('/appapi-auth-refreshtoken',{});
	if(ret.error_code == 0){
		let access_token=ret.data.access_token;
		let refresh_token=ret.data.refresh_token;
		header[uni.$cacheConfig.TOKENNAME]=access_token;
		uni.setStorageSync(uni.$cacheConfig.TOKENNAME,access_token);
		uni.setStorageSync(uni.$cacheConfig.REFRESH_TOKENNAME,refresh_token);
		let res =await $request(url,get,post,method);
		rosolve(res);
		return;
	}
	if(ret.error_code == 454555){
		uni.showModal({
			title: '温馨提示',
			content: ret.info,
			showCancel:false,
			success: function (res) {
				uni.redirectTo({url:loginPath});
			}
		});
		return;
	}
	//[刷新Token过期]跳转登录
	//uni.navigateTo({url:loginPath});
	uni.reLaunch({url:loginPath});
} 

/**
 * 上传专用[上传文件专用]
 * @param {Object} url
 * @param {Object} tempFile
 * @param {Object} param
 * @param {Object} requestName
 * @param {Object} rosolve
 */
async function refreshToken2(url,tempFile,param={},requestName='file',rosolve){
	let ret = await uni.$get('/appapi-auth-refreshtoken',{});
	if(ret.error_code == 0){
		let access_token=ret.data.access_token;
		let refresh_token=ret.data.refresh_token;
		header[uni.$cacheConfig.TOKENNAME]=access_token;
		uni.setStorageSync(uni.$cacheConfig.TOKENNAME,access_token);
		uni.setStorageSync(uni.$cacheConfig.REFRESH_TOKENNAME,refresh_token);
		let res =await $uploadFile(url,tempFile,param,requestName);
		rosolve(res);
		return;
	}
	//[刷新Token过期]跳转登录
	uni.navigateTo({url:loginPath});
} 

/**
 *  同步wx.login
 */
const wxLogin = () => {
    return new Promise((reslove) => {
      uni.login({
		provider: 'weixin',
        success(res) {
          reslove(res.code);
        },
        fail(){
            reslove('');
        },
        complete(){
            reslove('');
        }
      })
    })
}

/**
 * 上传
 * @param {*} url 
 * @param {*} tempFile 
 * @param {*} post 
 * @param {*} requestName 
 * 示例：
 *  async afterRead(event) {
 *    const { file } = event.detail;
 *    let res=await call.$uploadFile('member/upimages?width=200&height=200',file[i].tempFilePath);
 *    console.log(let);
 * }
 */
let $uploadFile = (url,tempFile,post={},requestName='file') =>{
	var path=url;
    let url2=setUrl(url,{});
    return new Promise((reslove,reject) => {
        uni.uploadFile({
            header:header,
            url: url2,
            filePath: tempFile,
            name: requestName,
            formData: post,
            success(res) {
                if(!res.data) return reslove(res);
                let data=JSON.parse(res.data);
                if(data.error_code == -3000){ //登录超时
					uni.setStorageSync(uni.$cacheConfig.TOKENNAME,null);
					let refresh_token=uni.getStorageSync(uni.$cacheConfig.REFRESH_TOKENNAME);
					if(refresh_token){
						header[uni.$cacheConfig.TOKENNAME]=refresh_token;
						return getToken2(path,tempFile,post,requestName,reslove);
					}
                    //[刷新Token过期]跳转登录
                    uni.navigateTo({url:loginPath});
                }else{
                    reslove(data);
                }
            }
        });
    })    
};

/**
 * 生成URL
 * @param {*} url 
 * @param {*} getObj 
 */
let setUrl=(url, getObj)=>{
    let httpRequestUrl=uni.$appConfig.HTTP_REQUEST_URL;
	let apiSignKey = uni.$appConfig.APP_KEY;
    if(url.indexOf('//:') == -1) {
        if(url.indexOf('?') > -1){
           let temp=url.split('?');
           url=temp[0];
           let temp2=temp[1].split('&');
           for(let i=0; i < temp2.length;i++){
               let temp3=temp2[i].split('=');
               getObj[temp3[0]]=temp3[1];
           }
        }
		if(url.substr(0,1) == '/') url=url.slice(1);
		if(!(httpRequestUrl.substr(httpRequestUrl.length-1,httpRequestUrl.length) == '/')){
			httpRequestUrl+='/';
		}
		url=httpRequestUrl+url;
    }
    getObj.time=parseInt(new Date().getTime() / 1000);
    let newkey=Object.keys(getObj).sort();
    let newObj = {};
    for (let i = 0; i < newkey.length; i++) {
      newObj[newkey[i]] = getObj[newkey[i]];
    }
    var get = '';
    for (var i in newObj) get += i + '=' + encodeURIComponent(newObj[i]) + '&';
    get = get.substring(0,get.length-1);
    get = '?' + get + '&sign=' + Md5.hex_md5(apiSignKey + get + apiSignKey);
	//console.log(url+get);
    return url+get;
}

/**
 * 全局GET请求
 */
let $get=(url,data={})=>{
	return $request(url,data,{},'GET')
}
/**
 * 全局POST请求
 */
let $post=(url,get={},data={})=>{
	return $request(url,get,data,'POST')
}
/**
 * 写入业务Token
 */
let $setToken=(access_token,refresh_token)=>{
	uni.setStorageSync(uni.$cacheConfig.TOKENNAME,access_token);
	uni.setStorageSync(uni.$cacheConfig.REFRESH_TOKENNAME,refresh_token);
	header[uni.$cacheConfig.TOKENNAME]=access_token;
	header[uni.$cacheConfig.REFRESH_TOKENNAME]=refresh_token;
}
/**
 * 销毁 Token
 */
let $unsetToken=()=>{
	uni.setStorageSync(uni.$cacheConfig.TOKENNAME,null);
	uni.setStorageSync(uni.$cacheConfig.REFRESH_TOKENNAME,null);
	//uni.setStorageSync(uni.$cacheConfig.DEVICE_ID,null);
	header[uni.$cacheConfig.TOKENNAME]='';
	header[uni.$cacheConfig.REFRESH_TOKENNAME]='';
	//header[uni.$cacheConfig.DEVICE_ID]='';
}
//同步获取设置信息
let $getSystemInfo=()=>{
	return new Promise((rosolve,reject)=>{
		uni.getSystemInfo({
			success: function(res) {
				rosolve(res);
			}
		})
	});
}
uni.$request=$request
uni.$get=$get
uni.$post=$post
uni.$uploadFile=$uploadFile
uni.$wxLogin=wxLogin
uni.$setToken=$setToken
uni.$unsetToken=$unsetToken
uni.$getSystemInfo=$getSystemInfo

